/**
 * 主题管理器
 * 负责主题切换、情感化样式应用和响应式适配
 */

/**
 * 主题配置接口
 */
const ThemeConfig = {
  name: '',
  displayName: '',
  colors: {
    primary: '',
    secondary: '',
    accent: '',
    background: '',
    surface: '',
    text: '',
    textSecondary: ''
  },
  gradients: {
    primary: '',
    secondary: '',
    accent: ''
  },
  shadows: {
    sm: '',
    md: '',
    lg: '',
    xl: ''
  },
  animations: {
    duration: '',
    easing: ''
  }
};

/**
 * 情感主题接口
 */
const EmotionTheme = {
  emotion: '',
  colors: {
    primary: '',
    secondary: '',
    background: ''
  },
  effects: {
    glow: '',
    particle: '',
    animation: ''
  }
};

/**
 * 响应式配置接口
 */
const ResponsiveConfig = {
  breakpoints: {
    xs: 0,
    sm: 0,
    md: 0,
    lg: 0,
    xl: 0
  },
  spacing: {
    xs: '',
    sm: '',
    md: '',
    lg: '',
    xl: ''
  },
  typography: {
    xs: '',
    sm: '',
    base: '',
    lg: '',
    xl: ''
  }
};

class ThemeManager {
  constructor() {
    this.currentTheme = 'default';
    this.currentEmotion = 'neutral';
    this.isDarkMode = false;
    this.isHighContrast = false;
  }
  deviceInfo = null;
  listeners = new Set();

  // 主题配置
  themes = {
    default: {
      name: 'default',
      displayName: '默认主题',
      colors: {
        primary: '#667eea',
        secondary: '#764ba2',
        accent: '#f093fb',
        background: '#ffffff',
        surface: '#f8f9fa',
        text: '#212121',
        textSecondary: '#757575'
      },
      gradients: {
        primary: 'linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%)',
        secondary: 'linear-gradient(135deg, #764ba2, #f093fb)',
        accent: 'linear-gradient(135deg, #f093fb, #667eea)'
      },
      shadows: {
        sm: '0 2rpx 8rpx rgba(0, 0, 0, 0.1)',
        md: '0 8rpx 25rpx rgba(0, 0, 0, 0.1)',
        lg: '0 20rpx 60rpx rgba(0, 0, 0, 0.1)',
        xl: '0 30rpx 80rpx rgba(0, 0, 0, 0.12)'
      },
      animations: {
        duration: '0.3s',
        easing: 'cubic-bezier(0.4, 0, 0.2, 1)'
      }
    },
    romantic: {
      name: 'romantic',
      displayName: '浪漫主题',
      colors: {
        primary: '#ff6b9d',
        secondary: '#c471ed',
        accent: '#12c2e9',
        background: '#fff5f8',
        surface: '#ffeef3',
        text: '#2d1b2e',
        textSecondary: '#8b5a6b'
      },
      gradients: {
        primary: 'linear-gradient(135deg, #ff6b9d 0%, #c471ed 100%)',
        secondary: 'linear-gradient(135deg, #c471ed, #12c2e9)',
        accent: 'linear-gradient(135deg, #12c2e9, #ff6b9d)'
      },
      shadows: {
        sm: '0 2rpx 8rpx rgba(255, 107, 157, 0.2)',
        md: '0 8rpx 25rpx rgba(255, 107, 157, 0.2)',
        lg: '0 20rpx 60rpx rgba(255, 107, 157, 0.2)',
        xl: '0 30rpx 80rpx rgba(255, 107, 157, 0.25)'
      },
      animations: {
        duration: '0.4s',
        easing: 'cubic-bezier(0.68, -0.55, 0.265, 1.55)'
      }
    },
    calm: {
      name: 'calm',
      displayName: '宁静主题',
      colors: {
        primary: '#4ecdc4',
        secondary: '#44a08d',
        accent: '#093637',
        background: '#f0fffe',
        surface: '#e6fffe',
        text: '#2c3e50',
        textSecondary: '#5d737e'
      },
      gradients: {
        primary: 'linear-gradient(135deg, #4ecdc4 0%, #44a08d 100%)',
        secondary: 'linear-gradient(135deg, #44a08d, #093637)',
        accent: 'linear-gradient(135deg, #093637, #4ecdc4)'
      },
      shadows: {
        sm: '0 2rpx 8rpx rgba(78, 205, 196, 0.15)',
        md: '0 8rpx 25rpx rgba(78, 205, 196, 0.15)',
        lg: '0 20rpx 60rpx rgba(78, 205, 196, 0.15)',
        xl: '0 30rpx 80rpx rgba(78, 205, 196, 0.2)'
      },
      animations: {
        duration: '0.5s',
        easing: 'cubic-bezier(0.25, 0.46, 0.45, 0.94)'
      }
    },
    energetic: {
      name: 'energetic',
      displayName: '活力主题',
      colors: {
        primary: '#ff9a56',
        secondary: '#ff6b6b',
        accent: '#4ecdc4',
        background: '#fffaf7',
        surface: '#fff2ec',
        text: '#2d3436',
        textSecondary: '#636e72'
      },
      gradients: {
        primary: 'linear-gradient(135deg, #ff9a56 0%, #ff6b6b 100%)',
        secondary: 'linear-gradient(135deg, #ff6b6b, #4ecdc4)',
        accent: 'linear-gradient(135deg, #4ecdc4, #ff9a56)'
      },
      shadows: {
        sm: '0 2rpx 8rpx rgba(255, 154, 86, 0.2)',
        md: '0 8rpx 25rpx rgba(255, 154, 86, 0.2)',
        lg: '0 20rpx 60rpx rgba(255, 154, 86, 0.2)',
        xl: '0 30rpx 80rpx rgba(255, 154, 86, 0.25)'
      },
      animations: {
        duration: '0.2s',
        easing: 'cubic-bezier(0.68, -0.55, 0.265, 1.55)'
      }
    }
  };

  // 情感主题配置
  emotionThemes = {
    happy: {
      emotion: 'happy',
      colors: {
        primary: '#ffd93d',
        secondary: '#ff6b9d',
        background: 'linear-gradient(135deg, #ffd93d 0%, #ff6b9d 100%)'
      },
      effects: {
        glow: '0 0 30rpx rgba(255, 217, 61, 0.6)',
        particle: '#ffd93d',
        animation: 'bounce 2s ease-in-out infinite'
      }
    },
    sad: {
      emotion: 'sad',
      colors: {
        primary: '#64b5f6',
        secondary: '#42a5f5',
        background: 'linear-gradient(135deg, #64b5f6 0%, #42a5f5 100%)'
      },
      effects: {
        glow: '0 0 30rpx rgba(100, 181, 246, 0.6)',
        particle: '#64b5f6',
        animation: 'float 3s ease-in-out infinite'
      }
    },
    angry: {
      emotion: 'angry',
      colors: {
        primary: '#f06292',
        secondary: '#e91e63',
        background: 'linear-gradient(135deg, #f06292 0%, #e91e63 100%)'
      },
      effects: {
        glow: '0 0 30rpx rgba(240, 98, 146, 0.6)',
        particle: '#f06292',
        animation: 'shake 0.5s ease-in-out infinite'
      }
    },
    calm: {
      emotion: 'calm',
      colors: {
        primary: '#4ecdc4',
        secondary: '#26a69a',
        background: 'linear-gradient(135deg, #4ecdc4 0%, #26a69a 100%)'
      },
      effects: {
        glow: '0 0 30rpx rgba(78, 205, 196, 0.6)',
        particle: '#4ecdc4',
        animation: 'pulse 2s ease-in-out infinite'
      }
    },
    excited: {
      emotion: 'excited',
      colors: {
        primary: '#ff9800',
        secondary: '#f57c00',
        background: 'linear-gradient(135deg, #ff9800 0%, #f57c00 100%)'
      },
      effects: {
        glow: '0 0 30rpx rgba(255, 152, 0, 0.6)',
        particle: '#ff9800',
        animation: 'heartbeat 1s ease-in-out infinite'
      }
    },
    love: {
      emotion: 'love',
      colors: {
        primary: '#e91e63',
        secondary: '#ad1457',
        background: 'linear-gradient(135deg, #e91e63 0%, #ad1457 100%)'
      },
      effects: {
        glow: '0 0 30rpx rgba(233, 30, 99, 0.6)',
        particle: '#e91e63',
        animation: 'heartbeat 1.5s ease-in-out infinite'
      }
    }
  };

  // 响应式配置
  responsiveConfig = {
    breakpoints: {
      xs: 320,
      sm: 480,
      md: 768,
      lg: 1024,
      xl: 1280
    },
    spacing: {
      xs: '8rpx',
      sm: '16rpx',
      md: '24rpx',
      lg: '32rpx',
      xl: '48rpx'
    },
    typography: {
      xs: '24rpx',
      sm: '28rpx',
      base: '32rpx',
      lg: '36rpx',
      xl: '40rpx'
    }
  };

  /**
   * 初始化主题管理器
   */
  async init() {
    try {
      // 获取设备信息
      this.deviceInfo = await this.getDeviceInfo();
      
      // 检测系统主题偏好
      this.detectSystemPreferences();
      
      // 加载保存的主题设置
      await this.loadSavedTheme();
      
      // 应用初始主题
      this.applyTheme(this.currentTheme);
      
      // 监听系统主题变化
      this.watchSystemThemeChanges();
      
    } catch (error) {
      console.error('主题管理器初始化失败:', error);
    }
  }

  /**
   * 获取设备信息
   */
  getDeviceInfo() {
    return new Promise((resolve) => {
      wx.getSystemInfo({
        success: (res) => {
          resolve({
            platform: res.platform,
            screenWidth: res.screenWidth,
            screenHeight: res.screenHeight,
            pixelRatio: res.pixelRatio,
            windowWidth: res.windowWidth,
            windowHeight: res.windowHeight,
            statusBarHeight: res.statusBarHeight,
            safeArea: res.safeArea,
            theme: res.theme || 'light'
          });
        },
        fail: () => {
          resolve({
            platform: 'unknown',
            screenWidth: 375,
            screenHeight: 667,
            pixelRatio: 2,
            windowWidth: 375,
            windowHeight: 667,
            statusBarHeight: 20,
            theme: 'light'
          });
        }
      });
    });
  }

  /**
   * 检测系统偏好设置
   */
  detectSystemPreferences() {
    if (this.deviceInfo) {
      this.isDarkMode = this.deviceInfo.theme === 'dark';
    }
    
    // 检测高对比度模式（如果支持）
    try {
      // 这里可以添加高对比度检测逻辑
      this.isHighContrast = false;
    } catch (error) {
      this.isHighContrast = false;
    }
  }

  /**
   * 加载保存的主题设置
   */
  async loadSavedTheme() {
    try {
      const savedTheme = wx.getStorageSync('app_theme');
      const savedEmotion = wx.getStorageSync('app_emotion');
      const savedDarkMode = wx.getStorageSync('app_dark_mode');
      
      if (savedTheme && this.themes[savedTheme]) {
        this.currentTheme = savedTheme;
      }
      
      if (savedEmotion && this.emotionThemes[savedEmotion]) {
        this.currentEmotion = savedEmotion;
      }
      
      if (typeof savedDarkMode === 'boolean') {
        this.isDarkMode = savedDarkMode;
      }
    } catch (error) {
      console.error('加载主题设置失败:', error);
    }
  }

  /**
   * 监听系统主题变化
   */
  watchSystemThemeChanges() {
    // 监听主题变化（如果支持）
    if (wx.onThemeChange) {
      wx.onThemeChange((res) => {
        this.isDarkMode = res.theme === 'dark';
        this.applyTheme(this.currentTheme);
        this.notifyListeners(this.currentTheme);
      });
    }
  }

  /**
   * 设置主题
   */
  setTheme(themeName) {
    if (!this.themes[themeName]) {
      console.warn(`主题 ${themeName} 不存在`);
      return;
    }
    
    this.currentTheme = themeName;
    this.applyTheme(themeName);
    this.saveThemeSettings();
    this.notifyListeners(themeName);
  }

  /**
   * 设置情感主题
   */
  setEmotionTheme(emotion) {
    if (!this.emotionThemes[emotion]) {
      console.warn(`情感主题 ${emotion} 不存在`);
      return;
    }
    
    this.currentEmotion = emotion;
    this.applyEmotionTheme(emotion);
    this.saveThemeSettings();
  }

  /**
   * 切换深色模式
   */
  toggleDarkMode() {
    this.isDarkMode = !this.isDarkMode;
    this.applyTheme(this.currentTheme);
    this.saveThemeSettings();
    this.notifyListeners(this.currentTheme);
  }

  /**
   * 设置深色模式
   */
  setDarkMode(enabled) {
    this.isDarkMode = enabled;
    this.applyTheme(this.currentTheme);
    this.saveThemeSettings();
    this.notifyListeners(this.currentTheme);
  }

  /**
   * 切换高对比度模式
   */
  toggleHighContrast() {
    this.isHighContrast = !this.isHighContrast;
    this.applyTheme(this.currentTheme);
    this.saveThemeSettings();
  }

  /**
   * 应用主题
   */
  applyTheme(themeName) {
    const theme = this.themes[themeName];
    if (!theme) return;
    
    const cssVars = this.generateCSSVariables(theme);
    this.applyCSSVariables(cssVars);
    
    // 设置页面属性
    this.setPageAttributes();
  }

  /**
   * 应用情感主题
   */
  applyEmotionTheme(emotion) {
    const emotionTheme = this.emotionThemes[emotion];
    if (!emotionTheme) return;
    
    const cssVars = this.generateEmotionCSSVariables(emotionTheme);
    this.applyCSSVariables(cssVars);
  }

  /**
   * 生成CSS变量
   */
  generateCSSVariables(theme) {
    const vars = {};
    
    // 基础颜色
    Object.entries(theme.colors).forEach(([key, value]) => {
      vars[`--${key.replace(/([A-Z])/g, '-$1').toLowerCase()}`] = value;
    });
    
    // 渐变
    Object.entries(theme.gradients).forEach(([key, value]) => {
      vars[`--gradient-${key}`] = value;
    });
    
    // 阴影
    Object.entries(theme.shadows).forEach(([key, value]) => {
      vars[`--shadow-${key}`] = value;
    });
    
    // 动画
    vars['--animation-duration'] = theme.animations.duration;
    vars['--animation-easing'] = theme.animations.easing;
    
    // 深色模式调整
    if (this.isDarkMode) {
      vars['--background'] = '#1a1a1a';
      vars['--surface'] = '#2d2d2d';
      vars['--text'] = '#ffffff';
      vars['--text-secondary'] = '#b0bec5';
    }
    
    // 高对比度调整
    if (this.isHighContrast) {
      vars['--text'] = this.isDarkMode ? '#ffffff' : '#000000';
      vars['--background'] = this.isDarkMode ? '#000000' : '#ffffff';
    }
    
    // 响应式调整
    const responsiveVars = this.generateResponsiveVariables();
    Object.assign(vars, responsiveVars);
    
    return vars;
  }

  /**
   * 生成情感CSS变量
   */
  generateEmotionCSSVariables(emotionTheme) {
    return {
      '--emotion-primary': emotionTheme.colors.primary,
      '--emotion-secondary': emotionTheme.colors.secondary,
      '--emotion-background': emotionTheme.colors.background,
      '--emotion-glow': emotionTheme.effects.glow,
      '--emotion-particle': emotionTheme.effects.particle,
      '--emotion-animation': emotionTheme.effects.animation
    };
  }

  /**
   * 生成响应式变量
   */
  generateResponsiveVariables() {
    const vars = {};
    const { windowWidth } = this.deviceInfo || { windowWidth: 375 };
    
    // 根据屏幕宽度调整间距和字体大小
    let scale = 1;
    if (windowWidth <= this.responsiveConfig.breakpoints.xs) {
      scale = 0.8;
    } else if (windowWidth <= this.responsiveConfig.breakpoints.sm) {
      scale = 0.9;
    } else if (windowWidth >= this.responsiveConfig.breakpoints.lg) {
      scale = 1.1;
    }
    
    // 应用缩放
    Object.entries(this.responsiveConfig.spacing).forEach(([key, value]) => {
      const numValue = parseInt(value.replace('rpx', ''));
      vars[`--spacing-${key}`] = `${Math.round(numValue * scale)}rpx`;
    });
    
    Object.entries(this.responsiveConfig.typography).forEach(([key, value]) => {
      const numValue = parseInt(value.replace('rpx', ''));
      vars[`--text-${key}`] = `${Math.round(numValue * scale)}rpx`;
    });
    
    return vars;
  }

  /**
   * 应用CSS变量
   */
  applyCSSVariables(vars) {
    // 在小程序中，我们需要通过其他方式应用CSS变量
    // 这里可以通过全局样式类或者动态样式来实现
    try {
      // 保存变量到全局
      getApp().globalData = getApp().globalData || {};
      getApp().globalData.themeVars = vars;
      
      // 触发页面重新渲染（如果需要）
      const pages = getCurrentPages();
      if (pages.length > 0) {
        const currentPage = pages[pages.length - 1];
        if (currentPage.setData) {
          currentPage.setData({
            themeVars: vars
          });
        }
      }
    } catch (error) {
      console.error('应用CSS变量失败:', error);
    }
  }

  /**
   * 设置页面属性
   */
  setPageAttributes() {
    try {
      // 设置页面数据属性
      const pages = getCurrentPages();
      if (pages.length > 0) {
        const currentPage = pages[pages.length - 1];
        if (currentPage.setData) {
          currentPage.setData({
            isDarkMode: this.isDarkMode,
            isHighContrast: this.isHighContrast,
            currentTheme: this.currentTheme,
            currentEmotion: this.currentEmotion
          });
        }
      }
    } catch (error) {
      console.error('设置页面属性失败:', error);
    }
  }

  /**
   * 保存主题设置
   */
  saveThemeSettings() {
    try {
      wx.setStorageSync('app_theme', this.currentTheme);
      wx.setStorageSync('app_emotion', this.currentEmotion);
      wx.setStorageSync('app_dark_mode', this.isDarkMode);
      wx.setStorageSync('app_high_contrast', this.isHighContrast);
    } catch (error) {
      console.error('保存主题设置失败:', error);
    }
  }

  /**
   * 添加主题变化监听器
   */
  addThemeChangeListener(callback) {
    this.listeners.add(callback);
  }

  /**
   * 移除主题变化监听器
   */
  removeThemeChangeListener(callback) {
    this.listeners.delete(callback);
  }

  /**
   * 通知监听器
   */
  notifyListeners(theme) {
    this.listeners.forEach(callback => {
      try {
        callback(theme);
      } catch (error) {
        console.error('主题变化监听器执行失败:', error);
      }
    });
  }

  /**
   * 获取当前主题
   */
  getCurrentTheme() {
    return this.currentTheme;
  }

  /**
   * 获取当前情感主题
   */
  getCurrentEmotion() {
    return this.currentEmotion;
  }

  /**
   * 获取可用主题列表
   */
  getAvailableThemes() {
    return Object.values(this.themes);
  }

  /**
   * 获取可用情感主题列表
   */
  getAvailableEmotions() {
    return Object.values(this.emotionThemes);
  }

  /**
   * 是否为深色模式
   */
  isDark() {
    return this.isDarkMode;
  }

  /**
   * 是否为高对比度模式
   */
  isHighContrastMode() {
    return this.isHighContrast;
  }

  /**
   * 获取设备信息
   */
  getDeviceInformation() {
    return this.deviceInfo;
  }

  /**
   * 获取响应式断点
   */
  getBreakpoint() {
    if (!this.deviceInfo) return 'md';
    
    const { windowWidth } = this.deviceInfo;
    
    if (windowWidth <= this.responsiveConfig.breakpoints.xs) {
      return 'xs';
    } else if (windowWidth <= this.responsiveConfig.breakpoints.sm) {
      return 'sm';
    } else if (windowWidth <= this.responsiveConfig.breakpoints.md) {
      return 'md';
    } else if (windowWidth <= this.responsiveConfig.breakpoints.lg) {
      return 'lg';
    } else {
      return 'xl';
    }
  }

  /**
   * 注册自定义主题
   */
  registerTheme(theme) {
    this.themes[theme.name] = theme;
  }

  /**
   * 注册自定义情感主题
   */
  registerEmotionTheme(emotionTheme) {
    this.emotionThemes[emotionTheme.emotion] = emotionTheme;
  }

  /**
   * 生成主题预览
   */
  generateThemePreview(themeName) {
    const theme = this.themes[themeName];
    if (!theme) return '';
    
    return `
      <div style="
        background: ${theme.gradients.primary};
        color: white;
        padding: 20rpx;
        border-radius: 16rpx;
        box-shadow: ${theme.shadows.md};
        text-align: center;
        font-size: 28rpx;
        font-weight: 500;
      ">
        ${theme.displayName}
      </div>
    `;
  }

  /**
   * 导出主题配置
   */
  exportThemeConfig() {
    return JSON.stringify({
      currentTheme: this.currentTheme,
      currentEmotion: this.currentEmotion,
      isDarkMode: this.isDarkMode,
      isHighContrast: this.isHighContrast,
      customThemes: Object.values(this.themes).filter(theme => 
        !['default', 'romantic', 'calm', 'energetic'].includes(theme.name)
      )
    }, null, 2);
  }

  /**
   * 导入主题配置
   */
  importThemeConfig(configJson) {
    try {
      const config = JSON.parse(configJson);
      
      if (config.currentTheme && this.themes[config.currentTheme]) {
        this.currentTheme = config.currentTheme;
      }
      
      if (config.currentEmotion && this.emotionThemes[config.currentEmotion]) {
        this.currentEmotion = config.currentEmotion;
      }
      
      if (typeof config.isDarkMode === 'boolean') {
        this.isDarkMode = config.isDarkMode;
      }
      
      if (typeof config.isHighContrast === 'boolean') {
        this.isHighContrast = config.isHighContrast;
      }
      
      if (config.customThemes && Array.isArray(config.customThemes)) {
        config.customThemes.forEach((theme) => {
          this.registerTheme(theme);
        });
      }
      
      this.applyTheme(this.currentTheme);
      this.saveThemeSettings();
      
      return true;
    } catch (error) {
      console.error('导入主题配置失败:', error);
      return false;
    }
  }
}

// 创建全局实例
const themeManager = new ThemeManager();

module.exports = themeManager;
module.exports.ThemeManager = ThemeManager;